package com.xxl.job.executor.service.jobhandler;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.bizsys.domain.AppUserMark;
import com.ruoyi.bizsys.service.IAppUserMarkService;
import com.ruoyi.bizsys.service.ILoanIouService;
import com.ruoyi.common.enums.UserTagEnum;
import com.ruoyi.common.utils.ObjectUtil;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Slf4j
@AllArgsConstructor
@Component
public class UserTagJob {

    private ILoanIouService loanIouService;

    private IAppUserMarkService userMarkService;

    @XxlJob("userTagJobHandler")
    public void run() {
        XxlJobHelper.log("用户标签任务 Start >>>>>>>>>>");

        runRepaymentNoApplyAgain();

        XxlJobHelper.log("用户标签任务 End >>>>>>>>>>");
    }

    /**
     * 用户还款后未再申请贷款
     * 1.  还款且逾期≤10天的用户（应还日期和还款日期）
     * 2.  还款后未再发起新的贷款
     */
    private void runRepaymentNoApplyAgain() {
        //还款且逾期≤10天的用户
        List<String> custList = loanIouService.selRepaymentNoApplyAgain();

        //限制sql长度
        int size = (custList.size() / 500) + 1;
        List<List<String>> lists = ObjectUtil.averageAssign(custList, size);
        Date date = new Date();
        lists.forEach(custNo -> {
            UpdateWrapper<AppUserMark> updateWrapper = new UpdateWrapper<AppUserMark>()
                    .in("cust_no", custNo)
                    .set("first_tag", UserTagEnum.NOT_WITHDRAW_AFTER_REPAYMENT.getFirstTag())
                    .set("second_tag", "")
                    .set("remark", "")
                    .set("update_time", date);
            userMarkService.update(updateWrapper);
        });

        //还款且逾期>10天的用户
        List<String> custListMoreThan10 = loanIouService.selRepaymentNoApplyAgainMoreThan10();
        //限制sql长度
        int sizeMoreThan10 = (custListMoreThan10.size() / 500) + 1;
        List<List<String>> listsMoreThan10 = ObjectUtil.averageAssign(custListMoreThan10, sizeMoreThan10);
        Date dateMoreThan10 = new Date();
        listsMoreThan10.forEach(custNo -> {
            UpdateWrapper<AppUserMark> updateWrapper = new UpdateWrapper<AppUserMark>()
                    .in("cust_no", custNo)
                    .set("first_tag", UserTagEnum.NOT_WITHDRAW_AFTER_REPAYMENT.getFirstTag())
                    .set("second_tag", UserTagEnum.NOT_WITHDRAW_AFTER_REPAYMENT.getSecondTag())
                    .set("remark", "").set("update_time", dateMoreThan10);
            userMarkService.update(updateWrapper);
        });
    }
}
